// pages/book-detail/index.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        active:0,
        isDesk:false,  //false代表未加入书桌
        deskid:''  //存储书桌表id
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let id = options.id || '62c7a4f95ee85713b0b8f240'
        // 加载图书详情
        getApp().fly.get(`/1.1/classes/Books?where={"objectId":"${id}"}`).then(res=>{
            // console.log(res);
            let obj = res.data.results[0]
            let uuid = obj.sourceUrl.substring(8)
            wx.request({
              url: `https://m.yuedu.163.com/reader/book/info.json?source_uuid=${uuid}&catalog_only=true`,
              success:(result)=>{
                  console.log(result);
                  obj.catalog = result.data.data.catalog
                  this.setData(obj)
              }
            })
            
        })
        //初始化书桌按钮状态
        let {userInfo} = getApp()
        if(!userInfo){return}
        let userid = userInfo.id
        let condition = {userid,bookid:id}
        condition = JSON.stringify(condition)
        getApp().fly.get(`/1.1/classes/BookDesk?where=${condition}`).then(res=>{
            // console.log(res);
            let {results} = res.data
            if(results.length){
                this.setData({isDesk:true,deskid:results[0].objectId})
            }
        })
    },
    onChange(ev){
        // console.log(ev);
        let {index} = ev.detail
        this.setData({active:index})
    },
    handleDesk(){
        let {userInfo} = getApp()
        if(!userInfo){
            getApp().handleLogin()
            return
        }
        let {objectId,title,iconUrl} = this.data
        getApp().fly.post('/1.1/classes/BookDesk',{ //向书桌表新增图书
            userid:userInfo.id,
            bookid:objectId,
            title,
            iconUrl
        }).then(res=>{
            // console.log(res);
            this.setData({isDesk:true,deskid:res.data.objectId})
        })
    },
    handleDel(){
        let {deskid} = this.data
        getApp().fly.delete(`/1.1/classes/BookDesk/${deskid}`).then(res=>{
            this.setData({isDesk:false})
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})